package uk.ac.cam.juliet.zedcat.client;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.LinkedList;

/**
 *
 * @author David Piggott
 */
public class Region extends LinkedList<Pixel> {

	private static final long serialVersionUID = -91541727824339070L;
	private final Frame mFrame;
	private final Configuration mConfiguration;

	public Region(Frame pF, Configuration c) {
		mFrame = pF;
		mConfiguration = c;
	}

	public Frame getFrame() {
		return mFrame;
	}

	// Doesn't work - doesn't matter since image signature system is not implemented
        // Also not necessarily the most efficient way of doing this
	public BufferedImage getImage() {
		Rectangle position = getLocation();
		BufferedImage image = mFrame.getSourceImage().getSubimage(position.x, position.y, position.width, position.height);
		boolean[][] pixelMask = new boolean[position.x][position.y];
		for(Pixel pixel : this) {
			pixelMask[pixel.getX()][pixel.getY()] = true;
		}
		for(int x = 0; x < mFrame.getSourceImage().getWidth(); x++) {
			for(int y = 0; y < mFrame.getSourceImage().getHeight(); y++) {
				if (pixelMask[x][y]) {
					image.setRGB(x, y, mConfiguration.getNullColour());
				}
			}
		}
		return image;
	}

	public Rectangle getLocation() {
		int leftBound = mFrame.getSourceImage().getWidth();
		int rightBound = 0;
		int topBound = mFrame.getSourceImage().getHeight();
		int bottomBound = 0;
		for(Pixel pixel : this) {
			if(pixel.getX() < leftBound) {
				leftBound = pixel.getX();
			}
			if(pixel.getX() > rightBound) {
				rightBound = pixel.getX();
			}
			if(pixel.getY() < topBound) {
				topBound = pixel.getY();
			}
			if(pixel.getY() > bottomBound) {
				bottomBound = pixel.getY();
			}
		}
		return new Rectangle(leftBound, topBound, rightBound - leftBound, bottomBound - topBound);
	}

}
